package cn.skyquant.quant4j.api.quant;

import cn.skyquant.quant4j.sdk.util.time.CalendarUtils;

import java.util.List;

public class MergeBar extends Bar {
    public final long begin;
    public final long end;

    public MergeBar(double open, double close, double high, double low, double volumn, long begin, long end) {
        super(open, close, high, low, volumn);
        this.begin = begin;
        this.end = end;
    }

    public static final MergeBar mergeBar(List<TimeBar> barList){
        if(barList==null || barList.size()==0){
            return null;
        }
        if(barList.size()==1){
            TimeBar bar = barList.get(0);
            MergeBar mergeBar = new MergeBar(bar.open,bar.close,bar.high,bar.low,bar.volumn,bar.time,bar.time);
            return mergeBar;
        }
        long begin = barList.get(0).time;
        double open = barList.get(0).open;
        double close = barList.get(barList.size()-1).close;
        long end = barList.get(barList.size()-1).time;
        double high = 0;
        double low = Double.MAX_VALUE;
        double volumn = 0;
        for(Bar b:barList){
            if(b.high> high){
                high = b.high;
            }
            if(b.low < low){
                low = b.low;
            }
            volumn += b.volumn;
        }
        MergeBar bar = new MergeBar(open,close,high,low,volumn,begin,end);
        return bar;
    }

    @Override
    public String toString() {
        return String.format("[%s %s] open=%s,close=%s,high=%s,low=%s", CalendarUtils.formatGMTStandard(begin),CalendarUtils.formatGMTStandard(end),open, close, high, low);
    }
}
